package com.start.platform.core.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.start.platform.core.entity.StartPlatformFans;
import com.start.platform.core.mappers.StartPlatformFansMapper;
import com.start.platform.core.service.StartPlatformFansService;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class StartPlatformFansServiceImpl extends ServiceImpl<StartPlatformFansMapper, StartPlatformFans> implements StartPlatformFansService {
    @Override
    public StartPlatformFans getFansByOpenId(String platformType, String appId, String openId) {
        LambdaQueryWrapper<StartPlatformFans> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StartPlatformFans::getPlatformType, platformType);
        lambdaQueryWrapper.eq(StartPlatformFans::getPlatformOpenId, openId);
        lambdaQueryWrapper.eq(StartPlatformFans::getPlatformAppId, appId);
        return getOne(lambdaQueryWrapper);
    }

    @Override
    public boolean hasFansByOpenId(String platformType, String appId, String openId) {
        LambdaQueryWrapper<StartPlatformFans> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StartPlatformFans::getPlatformType, platformType);
        lambdaQueryWrapper.eq(StartPlatformFans::getPlatformOpenId, openId);
        lambdaQueryWrapper.eq(StartPlatformFans::getPlatformAppId, appId);
        return count(lambdaQueryWrapper) > 0;
    }

    @Override
    public Map<String, Map<String, StartPlatformFans>> getUserFansMap(Serializable userId) {
        LambdaQueryWrapper<StartPlatformFans> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StartPlatformFans::getPlatformUserId, userId);
        List<StartPlatformFans> list = list(lambdaQueryWrapper);
        if (list.isEmpty()) {
            return new HashMap<>();
        }
        Map<String, List<StartPlatformFans>> map = list.stream().collect(Collectors.groupingBy(StartPlatformFans::getPlatformType));
        Map<String, Map<String, StartPlatformFans>> result = new HashMap<>();
        for (String key : map.keySet()) {
            List<StartPlatformFans> startPlatformFans = map.get(key);
            Map<String, StartPlatformFans> collect = startPlatformFans.stream().collect(Collectors.toMap(StartPlatformFans::getPlatformAppId, e -> e, (e1, e2) -> e2));
            result.put(key, collect);
        }
        return result;
    }
}
